package address

import (
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/controllers/login"
	USER "OnlineRetailers/models/User"
	error2 "OnlineRetailers/models/errorDeal"
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strconv"
	"time"
)

type PostAddress struct {
	beego.Controller
}

func (c *PostAddress) PostAddress() {

	defer func() {
		c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()

	var addr = "/Address/PostAddress"
	var err error

	address := &USER.Address{}
	log := &error2.Log{}
	mes := &error2.Mes{}
	//user:=&USER.WXUser{}
	o := orm.NewOrm()

	err = json.Unmarshal([]byte(c.GetString("address")), address)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	s := strconv.FormatInt(time.Now().Unix(), 10)
	address.AddressId = "ADD" + s
	err, openid := login.CheckOpenid(c.Ctx.Request.Header["Openid"])
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	sql := "select `open_id`,`address_id` from `w_x_user` where open_id=?"
	err = o.Raw(sql, openid).QueryRow(&address.User)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	//fmt.Println(key)
	if address.Default && address.User.Address.AddressId != address.AddressId {
		sql = "update `w_x_user` set address_id = ? where open_id =?"
		_, err := o.Raw(sql, address.AddressId, openid).Exec()
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
	}

	_, err = o.Insert(address)

	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "402", err, addr, err.Error())
		return
	}

	mes.Mes = "success"
	mes.Code = "200"
	c.Data["json"] = mes
}
